//
//  YWDetectAndUpkeepMissionCell.m
//  maintain
//
//  Created by Kyo on 16/9/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDetectAndUpkeepMissionCell.h"
#import "UIColor+CustomColors.h"
#import "UIImageView+WebCache.h"
#import "UIView+Extension.h"
#import "YWAnimationView.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWCommonTool.h"
#import "YWEquipmentManager.h"
#import "YWHandler.h"
#import "YWLoginTool.h"
#import "YWMacro.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWRoundImageView.h"
#import "Masonry.h"
#import "UILabel+AttributedText.h"
#import "YWContactManager.h"
#import "YWReplyManager.h"
#import "YWReply.h"

@interface YWDetectAndUpkeepMissionCell ()
//头像
//@property (weak, nonatomic) UIImageView* pictureImage;
//头像边的时间
@property (weak, nonatomic) UILabel* littleTimeLable;
//来自 fromPeopleLable
@property (weak, nonatomic) UILabel* fromPeopleLable;
//编号
@property (weak, nonatomic) UILabel *numberLabel;
//保养|检测 人
@property (weak, nonatomic) UILabel *executerManLabel;
////追踪 track
//@property (weak, nonatomic) UILabel *trackLable;
//设备名
@property (weak, nonatomic) UILabel* deviceNameLabel;
//位置
@property (weak, nonatomic) UILabel* locationLable;
//已巡查设备
@property (weak, nonatomic) UILabel* patrolEquipmentLable;
//保养|检测 设备总数
@property (weak, nonatomic) UILabel* equipmentForInspectionLable;
//截止时间endTimeLable
@property (weak, nonatomic) UILabel* endTimeLable;
//备注
@property (weak, nonatomic) UILabel *noteLabel;

@end
@implementation YWDetectAndUpkeepMissionCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    YWDetectAndUpkeepMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDetectAndUpkeepMissionCellIdentifier];
    if (cell == nil) {
        cell = [[YWDetectAndUpkeepMissionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:YWDetectAndUpkeepMissionCellIdentifier];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setUpSubviews];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //self.separatorInset = UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
    }
    return self;
}

- (void)setMaintenanceMission:(YWMaintenanceMission*)maintenanceMission
{
    _maintenanceMission = maintenanceMission;
    NSString* typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:maintenanceMission.maintenanceTypeId];
    NSInteger day = [YWCommonTool getDaysFrom:[NSDate date] To:[NSDate dateWithTimeIntervalSince1970:maintenanceMission.cutoffTime / 1000]];
    //    右上角时间
    NSString *time = nil;
    if (maintenanceMission.missionStatus==YWMissionStatusUnfinished) {
        time = [YWCommonTool showTimeWithNormalFormatter:maintenanceMission.createTime / 1000];
    }
    else {
        time = [YWCommonTool showTimeWithNormalFormatter:maintenanceMission.finishTime / 1000];
    }
    [_littleTimeLable labelText:@"分配时间: " withAttributedText:time andAttributedColor:[UIColor customYellowColor]];
    //    头像
//    NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:_maintenanceMission.creator.headIcon];
//    [_pictureImage sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
    //来自
    NSString *creator = maintenanceMission.creator.userName ? maintenanceMission.creator.userName : @"无";
    [self.fromPeopleLable labelText:@"分配人: " withAttributedText:creator andAttributedColor:[UIColor customYellowColor]];
    //    编号
    [_numberLabel labelText:@"编号: " withAttributedText:maintenanceMission.missionSequence ?:@"" andAttributedColor:[UIColor customYellowColor]];
    //执行人
    [_executerManLabel labelText:[NSString stringWithFormat:@"%@人: ",typeName] withAttributedText:[YWCommonTool handlerNamesWithHandlers:maintenanceMission.executors] andAttributedColor:[UIColor customYellowColor]];
    //    设备类型名
    [_deviceNameLabel labelText:@"设备: " withAttributedText:[[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:maintenanceMission.equipmentTypeId] andAttributedColor:[UIColor blackColor]];
    //    位置
    [_locationLable labelText:@"位置: " withAttributedText:[[YWBuildingManager shareManager] buildingWithId:maintenanceMission.buildingId].buildingName?:@"" andAttributedColor:[UIColor blackColor]];
    //检测设备总数
    [_equipmentForInspectionLable labelText:[NSString stringWithFormat:@"%@设备总数: ", typeName] withAttributedText:[NSString stringWithFormat:@"%ld个",(long)maintenanceMission.equipmentQuantity] andAttributedColor:[UIColor customYellowColor]];
    //已检测设备
    [_patrolEquipmentLable labelText:[NSString stringWithFormat:@"已%@设备: ", typeName] withAttributedText:[NSString stringWithFormat:@"%ld个",(long)maintenanceMission.completedQuantity] andAttributedColor:[UIColor customYellowColor]];
    //进度跟踪
//    if ([maintenanceMission.executorIds rangeOfString:[@([YWLoginTool loginUser].uniqueId) stringValue]].location == NSNotFound) {
//        _trackLable.text = @"进度跟踪";
//    }
//    else {
//        _trackLable.text = @"";
//    }
    //    截止时间
    [_endTimeLable labelText:@"截止时间: " withAttributedText:[YWCommonTool showTime:maintenanceMission.cutoffTime / 1000 andFormatter:KTimeFormatFullDate] andAttributedColor:[UIColor blackColor]];
    
    if (maintenanceMission.missionStatus == 1) {
        [self setShowFinishState:YWAnimationViewShowStatusFinished];
    }else if (day < 0) {
        [self setShowFinishState:YWAnimationViewShowStatusExpired];
    }
    else if (day < kMaxExpireDay) {
        [self setShowFinishState:YWAnimationViewShowStatusExpire];
    }
    else {
        [self setShowFinishState:YWAnimationViewShowStatusUnfinish];
    }
    //状态图类型
    _statusImageview.type = YWAnimationViewTypeRectangle;
    //备注
    [_noteLabel labelText:@"备注: " withAttributedText:maintenanceMission.note.length ? maintenanceMission.note: @"无" andAttributedColor:[UIColor blackColor]];
    //任务参与人，要把报障人算进去
    NSMutableArray *tempArray = [NSMutableArray array];
    NSMutableArray *observerArray = [NSMutableArray array];
    [tempArray addObject:maintenanceMission.creator];
    [tempArray addObjectsFromArray:maintenanceMission.executors];
    [tempArray addObjectsFromArray:maintenanceMission.observers];
    for (YWHandler *handler in tempArray) {
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[observerArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==0) {
            [observerArray addObject:handler];
        }
    }
    NSString * firstStr = [NSString stringWithFormat:@"参与人(%ld): ",(long)observerArray.count];
    NSMutableString *observerName = [[NSMutableString alloc] init];
    [observerArray enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (observerName.length && idx!=0) {
            [observerName appendString:@" "];
        }
        [observerName appendString:handler.userName];
    }];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@",observerName?:@""];//参与者要加进来
    
    self.observersLabel.attributedText = [YWCommonTool attributedTextWithFirstText:firstStr firstColor:[UIColor customTextGrayBlackColor] secondText:nameStr secondColor:[UIColor customBlueColor] font:kContentFont];
    //有评论
    NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:maintenanceMission.missionId andRelationType:YWReplyRelationTypeDetectAndUpkeep];
    if (commentArray.count>0) {
        YWReply * reply = [commentArray firstObject];
        NSString * replyCount = [NSString stringWithFormat:@"评论(%ld): ",commentArray.count];
        //    时间
        NSString * timeStr = [YWCommonTool recordDateByFormatTimeString:reply.replyTime/1000 showYear:YES];
        //    内容
        
        NSString *atUserName = reply.atUser.userName.length>0?[NSString stringWithFormat:@" @%@",reply.atUser.userName]:@"";
        NSString * content = atUserName.length?[NSString stringWithFormat:@" %@  ",reply.content.length>0?reply.content:@""] : (reply.content.length>0?reply.content:@"");
        
        self.replyLabel.attributedText = [YWCommonTool attributedTextWithFirstText:replyCount firstColor:[UIColor customTextGrayColor] firstFont:kContentFont secondText:reply.replier.userName secondColor:[UIColor customBlueColor] secFont:kContentFont thirdText:atUserName thirdColor:[UIColor customBlueColor] thirdFont:kContentFont fourthText:content fourthColor:[UIColor blackColor] fourFont:kContentFont fifthText:timeStr fifthColor:[UIColor customTextGrayColor] fifthFont:[UIFont systemFontOfSize:13]];
    }else{
        self.replyLabel.attributedText = nil;
    }

    _executerManLabel.preferredMaxLayoutWidth = _executerManLabel.frame.size.width;
    _deviceNameLabel.preferredMaxLayoutWidth = _deviceNameLabel.frame.size.width;
    _locationLable.preferredMaxLayoutWidth = _locationLable.frame.size.width;
    _noteLabel.preferredMaxLayoutWidth = _noteLabel.frame.size.width;
    self.observersLabel.preferredMaxLayoutWidth = self.observersLabel.frame.size.width;
    self.replyLabel.preferredMaxLayoutWidth = self.replyLabel.frame.size.width;
}

- (void)setShowFinishState:(YWAnimationViewShowStatus)animationViewShowStatus
{
    self.statusImageview.showStatus = animationViewShowStatus;
}

- (void)setUpSubviews {
    UIView *superview = self.contentView;
    /**
     *  头像 名字
     *  头像 时间
     */
//    [self.pictureImage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.top.mas_equalTo(superview).offset(8);
//        make.width.and.height.mas_equalTo(@46);
//    }];
    
    [self.fromPeopleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.mas_equalTo(superview).offset(8);
    }];
    
    [self.littleTimeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_fromPeopleLable);
        make.top.mas_equalTo(_fromPeopleLable.mas_bottom).offset(4);
    }];
    /**
     *  编号
     *  检测人  进度追踪
     *  设备
     *  位置
     *  检测设备总数  已检测设备
     *  截止时间
     *  备注
     */
    
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_littleTimeLable.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.executerManLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_numberLabel.mas_bottom).offset(6);
    }];
    
//    [self.trackLable mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(_executerManLabel);
//        make.width.mas_equalTo(@64);
//        make.right.mas_equalTo(superview).offset(-8);
//    }];
    
    [self.deviceNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_executerManLabel.mas_bottom).offset(6);
    }];
    
    [self.locationLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_deviceNameLabel.mas_bottom).offset(6);
    }];
    
    [self.equipmentForInspectionLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_locationLable.mas_bottom).offset(6);
        make.left.mas_equalTo(_numberLabel);
        make.right.mas_equalTo(superview.mas_centerX).offset(10);
    }];
    
    [self.patrolEquipmentLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.baseline.mas_equalTo(_equipmentForInspectionLable);
        make.left.mas_equalTo(superview.mas_centerX).offset(15);
    }];
    
    [self.endTimeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_equipmentForInspectionLable.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(@[_numberLabel, _executerManLabel, _deviceNameLabel, _locationLable]);
    }];
    
    
    [self.noteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_endTimeLable.mas_bottom).offset(6);
        make.left.mas_equalTo(_numberLabel);
        make.right.mas_equalTo(superview).offset(-75);
//        make.bottom.mas_equalTo(superview.mas_bottom).offset(-5);
    }];
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_noteLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(superview);
        make.height.mas_equalTo(@1.0);
    }];
    
    [self.observersLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.separatorLineView.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_numberLabel);
    }];
    [self.replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.observersLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_numberLabel);
        make.bottom.mas_equalTo(superview).offset(-6);
    }];
    
    [self.statusImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
        make.right.and.bottom.mas_equalTo(superview);
    }];
}

- (UILabel *)fromPeopleLable{
    if (!_fromPeopleLable) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _fromPeopleLable = label;
        [self.contentView addSubview:_fromPeopleLable];
    }
    return _fromPeopleLable;
}

- (UILabel *)littleTimeLable{
    if (!_littleTimeLable) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _littleTimeLable = label;
        [self.contentView addSubview:_littleTimeLable];
    }
    return _littleTimeLable;
}

- (UILabel *)numberLabel{
    if (!_numberLabel) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _numberLabel = label;
        [self.contentView addSubview:_numberLabel];
    }
    return _numberLabel;
}

- (UILabel *)executerManLabel{
    if (!_executerManLabel) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _executerManLabel = label;
        [self.contentView addSubview:_executerManLabel];
    }
    return _executerManLabel;
}

//- (UILabel *)trackLable{
//    if (!_trackLable) {
//        UILabel *label = [[UILabel alloc] init];
//        label.font = kContentFont;
//        label.textColor = [UIColor customBlueColor];
//        _trackLable = label;
//        [self.contentView addSubview:_trackLable];
//    }
//    return _trackLable;
//}

- (UILabel *)deviceNameLabel{
    if (!_deviceNameLabel) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _deviceNameLabel = label;
        [self.contentView addSubview:_deviceNameLabel];
    }
    return _deviceNameLabel;
}

- (UILabel *)locationLable{
    if (!_locationLable) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _locationLable = label;
        [self.contentView addSubview:_locationLable];
    }
    return _locationLable;
}


- (UILabel *)equipmentForInspectionLable{
    if (!_equipmentForInspectionLable) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _equipmentForInspectionLable = label;
        [self.contentView addSubview:_equipmentForInspectionLable];
    }
    return _equipmentForInspectionLable;
}

- (UILabel *)patrolEquipmentLable{
    if (!_patrolEquipmentLable) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _patrolEquipmentLable = label;
        [self.contentView addSubview:_patrolEquipmentLable];
    }
    return _patrolEquipmentLable;
}

- (UILabel *)endTimeLable{
    if (!_endTimeLable) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _endTimeLable = label;
        [self.contentView addSubview:_endTimeLable];
    }
    return _endTimeLable;
}

- (UILabel *)noteLabel{
    if (!_noteLabel) {
        UILabel *label = [[UILabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _noteLabel = label;
        [self.contentView addSubview:_noteLabel];
    }
    return _noteLabel;
}

-(YWAnimationView *)statusImageview{
    if (!_statusImageview) {
        YWAnimationView *imageView = [YWAnimationView new];
        _statusImageview = imageView;
        [self.contentView addSubview:_statusImageview];
    }
    return _statusImageview;
}

@end
